# -*- coding: utf-8 -*-
import os
import time
import json
import logging
from alipay import AliPay

_LOGGER = logging.getLogger('alipay')


def get_ali_certs():
    path = '/opt/bigbang/ali6'
    return (
        os.path.join(path, "ali_private_key_pkcs8.pem"),
        os.path.join(path, "ali_public_key.pem")
    )


def get_ali2_certs():
    path = '/opt/bigbang/ali2'
    return (
        os.path.join(path, "ali_private_key_pkcs8.pem"),
        os.path.join(path, "ali_public_key.pem")
    )


__ali_private_key_path, __ali_public_key_path = get_ali_certs()
alipay = AliPay(
    appid="2017120900480004",
    app_notify_url = '',
    app_private_key_path=__ali_private_key_path,
    alipay_public_key_path=__ali_public_key_path,
    sign_type='RSA2'
)


__ali2_private_key_path, __ali2_public_key_path = get_ali2_certs()
alipay2 = AliPay(
    appid="2017063007609988",
    app_notify_url = '',
    app_private_key_path=__ali2_private_key_path,
    alipay_public_key_path=__ali2_public_key_path,
    sign_type='RSA2'
)

ALIPAY_LIST = [{
    'no': '2017120900480004',
    'handler': alipay,
    'payer': u'成都壹控网络科技有限公司'
},{
    'no': '2017063007609988',
    'handler': alipay2,
    'payer': u'东莞市环泽电子科技有限公司'
}]


def choose_payer(order_id):
    choose_index = sum([int(i) for i in str(order_id)[-3:]]) % len(ALIPAY_LIST)
    return ALIPAY_LIST[choose_index]


def trans_to_account(chosed_payer, order_id, amount, alipay_no, payee_real_name, remark=''):
    _LOGGER.info(u'Auto trans alipay, ready to trans %s %s %s', order_id, alipay_no, amount)
    _LOGGER.info(u'payer {} choosed, amount {}'.format(chosed_payer['payer'], amount))
    return chosed_payer['handler'].api_alipay_fund_trans_toaccount_transfer(out_biz_no=order_id,
                               payee_type='ALIPAY_LOGONID',
                               payee_account=alipay_no,
                               payee_real_name=payee_real_name,
                               amount=amount,
                               payer_real_name=chosed_payer['payer'],
                               remark=remark,
                               ext_param=json.dumps({"order_title": u"商城"},
                                                    ensure_ascii=False))


